//
//  SHYMediator.m
//  SHYMediator
//
//  Created by huangyang on 16/6/27.
//  Copyright © 2016年 mucang. All rights reserved.
//

#import "SHYMediator.h"
//#import "Target_A.h"
@implementation SHYMediator

#pragma mark - public methods

+(instancetype)shareInstance {
    static SHYMediator* mediator;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mediator = [[SHYMediator alloc] init];
    });
    return mediator;
}

-(id)performActionWithUrl:(NSURL *)url completion:(void (^)(NSDictionary *))completion {
    if (![url.scheme isEqualToString:@"SHYMediator"]) {
        return @(NO);
    }
    
    NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
    NSString* urlString = [url query];
    for (NSString* param in [urlString componentsSeparatedByString:@"&"]) {
        NSArray* elts = [param componentsSeparatedByString:@"="];
        if ([elts count] < 2)
            continue;
        [params setObject:[elts lastObject] forKey:[elts firstObject]];
    }
    
    NSString* actionName = [url.path stringByReplacingOccurrencesOfString:@"/" withString:@""];
    if ([actionName hasPrefix:@"native"]) {
        return @(NO);
    }
    
    id result = [self performTarget:url.host action:actionName params:params];
    if (completion) {
        if (result) {
            completion(@{@"result":result});
        }
        else {
            completion(nil);
        }
    }
    return result;
}

-(id)performTarget:(NSString *)targetName action:(NSString *)actionName params:(NSDictionary *)params {
    
    NSString* targetClassString = [NSString stringWithFormat:@"Target_%@",targetName];
    NSString* actionString = [NSString stringWithFormat:@"Action_%@:",actionName];
    
    Class targetClass = NSClassFromString(targetClassString);
    id target=[[targetClass alloc] init];
    SEL action = NSSelectorFromString(actionString);
    
    if (target == nil) {
        return nil;
    }
    
    if ([target respondsToSelector:action]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        return [target performSelector:action withObject:params];
#pragma clang diagnostic pop
    }
    else {
        SEL action = NSSelectorFromString(@"notFound:");
        if ([target respondsToSelector:action]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
            return [target performSelector:action withObject:params];
#pragma clang diagnostic pop
        }
        else {
            return nil;
        }
    }
}

@end
